from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.core.paginator import Paginator
from .models import Comment
from .serializers import CommentSerializer, CommentCreateSerializer
from apps.articles.models import Like
from apps.users.models import UserMessage
from utils.response import success_response, error_response
from utils.oss_utils import get_oss_uploader
import logging

logger = logging.getLogger(__name__)


@api_view(['POST'])
@permission_classes([AllowAny])
def get_comments(request):
    """获取评论"""
    try:
        article_id = request.data.get('articleId')
        order_type = int(request.data.get('orderType', 0))
        page_no = int(request.data.get('pageNo', 1))
        page_size = int(request.data.get('pageSize', 50))

        if not article_id:
            return error_response(message="Article ID cannot be empty")

        # 只获取顶级评论
        queryset = Comment.objects.filter(article__article_id=article_id, p_comment_id=0)

        # 排序
        if order_type == 0:  # 按时间排序（最新的在前）
            queryset = queryset.order_by('-top_type', '-post_time')
        elif order_type == 1:  # 按点赞数排序
            queryset = queryset.order_by('-top_type', '-good_count', '-post_time')

        # 分页
        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page_no)

        serializer = CommentSerializer(page_obj.object_list, many=True, context={'request': request})

        return success_response({
            'totalCount': paginator.count,
            'pageSize': page_size,
            'pageNo': page_no,
            'pageTotal': paginator.num_pages,
            'list': serializer.data
        })
    except Exception as e:
        return error_response(message=str(e))


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def publish_comment(request):
    """发布评论"""
    data = request.data.copy()
    data['userId'] = request.user.user_id
    
    # 检查文章是否允许评论
    article_id = data.get('articleId')
    if not article_id:
        return error_response(message="Article ID cannot be empty")
    
    try:
        from apps.articles.models import Article
        article = Article.objects.get(article_id=article_id)
        if not article.allow_comments:
            return error_response(message="This article does not allow comments")
    except Article.DoesNotExist:
        return error_response(message="Article does not exist")
    
    serializer = CommentCreateSerializer(data=data)
    if serializer.is_valid():
        comment = serializer.save()
        
        # 发送回复通知
        p_comment_id = data.get('pCommentId', 0)
        if p_comment_id and p_comment_id != 0:
            # 回复评论
            try:
                parent_comment = Comment.objects.get(comment_id=p_comment_id)
                if parent_comment.user != request.user:  # 不给自己发通知
                    UserMessage.objects.create(
                        received_user_id=str(parent_comment.user.user_id),
                        article_id=str(comment.article.article_id),
                        article_title=comment.article.title,
                        comment_id=comment.comment_id,
                        send_user_id=str(request.user.user_id),
                        send_nick_name=request.user.nickname,
                        message_type=2,  # 回复评论
                        message_content=f"{request.user.nickname} replied to your comment",
                        status=0  # 未读
                    )
            except Comment.DoesNotExist:
                pass
        else:
            # 回复文章
            if comment.article.user != request.user:  # 不给自己发通知
                UserMessage.objects.create(
                    received_user_id=str(comment.article.user.user_id),
                    article_id=str(comment.article.article_id),
                    article_title=comment.article.title,
                    comment_id=comment.comment_id,
                    send_user_id=str(request.user.user_id),
                    send_nick_name=request.user.nickname,
                    message_type=1,  # 回复帖子
                    message_content=f"{request.user.nickname} replied to your post",
                    status=0  # 未读
                )
        
        # 返回创建的评论信息
        response_serializer = CommentSerializer(comment, context={'request': request})
        return success_response(data=response_serializer.data, message="Comment posted successfully")
    return error_response(message=str(serializer.errors))


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def do_like_comment(request):
    """点赞评论"""
    comment_id = request.data.get('commentId')
    
    if not comment_id:
        return error_response(message="Comment ID cannot be empty")
    
    try:
        comment = Comment.objects.get(comment_id=comment_id)
        
        # 检查是否已点赞
        like_obj, created = Like.objects.get_or_create(
            like_type=1,
            object_id=comment_id,
            user=request.user,
            defaults={'author_user_id': str(comment.user.user_id)}
        )
        
        if created:
            # 新增点赞，增加点赞数
            comment.good_count += 1
            comment.save()
            like_type = 1
            
            # 给评论作者发送点赞通知（不给自己发通知）
            if comment.user != request.user:
                UserMessage.objects.create(
                    received_user_id=str(comment.user.user_id),
                    article_id=str(comment.article.article_id),
                    article_title=comment.article.title,
                    comment_id=comment_id,
                    send_user_id=str(request.user.user_id),
                    send_nick_name=request.user.nickname,
                    message_type=4,  # 点赞评论
                    message_content=f"{request.user.nickname} liked your comment",
                    status=0  # 未读
                )
        else:
            # 已存在，取消点赞
            like_obj.delete()
            comment.good_count = max(0, comment.good_count - 1)
            comment.save()
            like_type = 0
        
        # 返回更新后的评论信息
        response_serializer = CommentSerializer(comment, context={'request': request})
        response_data = response_serializer.data
        response_data['likeType'] = like_type
        
        return success_response(data=response_data, message="Operation successful")
    except Comment.DoesNotExist:
        return error_response(message="Comment does not exist")


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_top_type(request):
    """置顶/取消置顶评论"""
    comment_id = request.data.get('commentId')
    top_type = request.data.get('topType')
    
    if not comment_id:
        return error_response(message="Comment ID cannot be empty")
    
    try:
        comment = Comment.objects.get(comment_id=comment_id)
        
        # 检查权限
        if comment.article.user != request.user:
            return error_response(message="No permission to perform this operation")
        
        comment.top_type = top_type
        comment.save()
        
        return success_response(message="Operation successful")
    except Comment.DoesNotExist:
        return error_response(message="Comment does not exist")


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_comment_image(request):
    """上传评论图片到阿里云OSS"""
    try:
        # 检查是否有上传的文件
        if 'image' not in request.FILES:
            return error_response(message="Please select an image to upload")
        
        image_file = request.FILES['image']
        
        # 验证文件类型
        allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
        if image_file.content_type not in allowed_types:
            return error_response(message=f"Unsupported image format. Supported formats: {', '.join(allowed_types)}")
        
        # 验证文件大小（限制10MB）
        max_size = 10 * 1024 * 1024
        if image_file.size > max_size:
            return error_response(message="Image size cannot exceed 10MB")
        
        # 验证文件名
        if not image_file.name:
            return error_response(message="File name cannot be empty")
        
        # 获取OSS上传器
        uploader = get_oss_uploader()
        if not uploader:
            logger.error("OSS uploader initialization failed")
            return error_response(message="Image upload service is temporarily unavailable", code=500)
        
        # 上传到OSS
        image_url = uploader.upload_file(image_file, folder='comments')
        
        if image_url:
            
            logger.info(f"User {request.user.user_id} uploaded comment image successfully: {image_url}")
            return success_response({
                'imageUrl': image_url,
                'fileName': image_file.name,
                'fileSize': image_file.size
            }, message="Image uploaded successfully")
        else:
            logger.error(f"User {request.user.user_id} comment image upload failed")
            return error_response(message="Image upload failed, please try again", code=500)
            
    except Exception as e:
        logger.error(f"Comment image upload exception: {e}")
        return error_response(message="Image upload exception, please try again", code=500)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def delete_comment_image(request):
    """删除评论图片"""
    try:
        image_url = request.data.get('image_url')
        
        if not image_url:
            return error_response("Image URL cannot be empty")
        
        # 获取OSS上传器
        oss_uploader = get_oss_uploader()
        if not oss_uploader:
            return error_response("OSS service initialization failed")
        
        # 删除OSS中的文件
        success = oss_uploader.delete_file(image_url)
        
        if success:
            
            logger.info(f"User {request.user.user_id} deleted comment image successfully: {image_url}")
            return success_response("Image deleted successfully")
        else:
            return error_response("Image deletion failed")
            
    except Exception as e:
        logger.error(f"Delete comment image failed: {e}")
        return error_response("Deletion failed, please try again")